package com.lu.study.lu.base.framework.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;

/**
 * @CreateDate 2022/4/22 15:53 (星期五)
 * @ClassName SpringContextUtil
 * @Name
 * @Author RaoLuPing
 * @Version 1.0
 * @Description 获取spring的上下文。 使用事项 必须在请求中
 **/

public class SpringContextUtil {

    /**
     * 不允许自行实例化
     */
    private SpringContextUtil() {

    }

    private static ApplicationContext applicationContext;

    /**
     * 通过springboot启动的方式注入 spring上下文
     *
     * @param context
     */
    public static void setApplicationContext(ApplicationContext context) {
        applicationContext = context;
    }

    public final static ApplicationContext getApplicationContext() {
        if (null == applicationContext) {
            Object attribute = RequestContextHolder.getRequestAttributes().getAttribute("org.springframework.web.servlet.DispatcherServlet.CONTEXT", 0);
            if (null == attribute) {
                return null;
            }
            ApplicationContext applicationContext = (ApplicationContext) attribute;
            return applicationContext;
        } else {

            return applicationContext;
        }
    }


    /**
     * 根据beanName 获取 ioc中实例
     *
     * @param name beanName eg： xxxService
     * @return
     * @throws BeansException
     */
    public final static Object getBean(String name) throws BeansException {
        return getApplicationContext().getBean(name);
    }


    /**
     * 根据beanName 和classType获取 ioc中实例
     *
     * @param name         beanName eg： xxxService
     * @param requiredType classType eg: XxxService.class
     * @param <T>
     * @return
     * @throws BeansException
     */
    public final static <T> T getBean(String name, Class<T> requiredType) throws BeansException {
        return getApplicationContext().getBean(name, requiredType);
    }


    /**
     * 根据classType获取 ioc中实例
     *
     * @param requiredType classType eg:XxxService.class
     * @param <T>
     * @return
     * @throws BeansException
     */
    public final static <T> T getBean(Class<T> requiredType) throws BeansException {
        return getApplicationContext().getBean(requiredType);
    }


}
